<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="模块名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入模块名称" />
      </el-form-item>
      <el-form-item label="使用范围" prop="type">
        <el-select v-model="formData.type">
          <el-option label="全公司" :value="0"></el-option>
          <el-option label="指定部门" :value="1"></el-option>
          <el-option label="指定员工" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择部门" v-if="formData.type == 1">
        <DeptTree
          ref="deptThree"
          :show-checkbox="true"
          :show-search="false"
          @current-change="currentChange"
        />
      </el-form-item>

      <el-form-item label="选择员工" v-if="formData.type == 2">
        <el-select
          v-model="selectUserId"
          multiple
          placeholder="Select"
          style="width: 240px"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用"  prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1" :value="1">启用</el-radio>
          <el-radio :label="0" :value="0">不启用</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- TODO: 补充一个部门和员工选择器， 仅选择部门 、 仅选择员工 -->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as ModuleApi from '@/api/crm/module'
import DeptTree from '@/views/system/user/DeptTree.vue'
import * as UserApi from '@/api/system/user'

defineOptions({ name: 'ModuleForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const isShowStatus = ref(false) // 是否显示启用状态
const formData = ref({
  id: undefined,
  name: undefined,
  type: undefined,
  deptIds: undefined,
  userIds: undefined,
  status: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '模块名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '使用范围不能为空', trigger: 'change' }],
  status: [{ required: true, message: '是否启用为必选项', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref
const userOptions = ref([])
const getUserOption = async () => {
  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
}
const selectUserId = ref(null)

const deptThree = ref(null) // 菜单树组件 Ref
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ModuleApi.getModule(id)
      if(formData.value.type == 1) {
        nextTick(() => {
          deptThree.value.setCheckedKeys(formData.value.deptIds.split(','))
        })
      }
      if(formData.value.type == 2) {
        formData.value.userIds = formData.value.userIds.split(',')
        formData.value.userIds.pop()
        formData.value.userIds.shift()
        selectUserId.value = formData.value.userIds.map(i=>{
          return i-0
        })
      }
    } finally {
      formLoading.value = false
    }
  }
  getUserOption()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  if (formData.value.type == 2) {
    formData.value.userIds = ',' + selectUserId.value.join(',') + ','
  }
  try {
    const data = formData.value as unknown as ModuleApi.ModuleVO
    if (formType.value === 'create') {
      await ModuleApi.createModule(data)
      message.success(t('common.createSuccess'))
    } else {
      await ModuleApi.updateModule(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success', formData.value.id, '1')
  } finally {
    formLoading.value = false
  }
}

// 树形选择 右侧的表格选中
const currentChange = (checkNodes, value) => {
  let keys = value.checkedKeys
  formData.value.deptIds = ',' + keys.join(',') + ','
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    type: undefined,
    deptIds: undefined,
    userIds: undefined,
    status: undefined,
  }
  formRef.value?.resetFields()
}
</script>
